<template>
  <div class="container-column">
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="getData('reset')">
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="渠道商编码" style="width: 100%;">
                    <el-input @keyup.enter.native="getData('search')" @clear="getData('search')"
                      v-model="listSearch.condition.channelMerchantCode" clearable placeholder="请输入渠道商编码" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="渠道商名称">
                    <el-input @keyup.enter.native="getData('search')" @clear="getData('search')"
                      v-model="listSearch.condition.channelMerchantName" clearable placeholder="请输入渠道商名称" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="渠道商联系人">
                    <el-input v-model="listSearch.condition.contactName" clearable
                      @keyup.enter.native="getData('search')" @clear="getData('search')" placeholder="请输入渠道商联系人" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="所在地-省">
                    <el-cascader :options="twoLevelCity" @change="changeValue" v-model="cityCode"
                      :props="{ checkStrictly: true, value: 'dictItemCode', label: 'dictItemName', children: 'childrenDictItemList', }"
                      clearable></el-cascader>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="getData('search')">查询</el-button>
                <el-button @click="getData('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>
            <el-button :icon="Plus" v-permission="'CHANNEL_MERCHANT:CREATE-EDIT'" type="primary"
              @click="addEdit('add')"></el-button>
            <el-button :icon="listSearch.isShow ? Hide : View" 
              @click="handleView" :title="listSearch.isShow ? '隐藏敏感数据' : '查看敏感数据'"></el-button>
            <DropItem v-model:table-prop="tableProp"></DropItem>
         
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageData.total" @get-page="handPage"
          :tableData="pageData.tableData" :tableHeight="pageData.tableHeight" :loading="pageData.loadIng">
          <template #handle="scope">
           
            <el-button type="primary" size="small" v-permission="'CHANNEL_MERCHANT:CREATE-EDIT'" link
              @click="addEdit('edit', scope.row)">编辑</el-button>
            <el-button type="danger" size="small" v-permission="'CHANNEL_MERCHANT:DELETE'" link
              @click="DeleteBtn(scope.row)">删除</el-button>
              <el-button type="primary" size="small" v-permission="'CHANNEL_MERCHANT:DETAIL'" link
              @click="detailBtn(scope.row)">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <addBusiness ref="addEditRef" @refresh="getData('reset')" @searchEdit="getData('search')"></addBusiness>
    <downList ref="downListRef"></downList>
    <!-- <FormDetail ref="detailRef" :detailData="detailData" :labelWidth="140"></FormDetail> -->
     <detailForm ref="detailRef"></detailForm>
  </div>
</template>

<script lang="ts" setup>
/***************************************引入******************************************** */
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { ref, reactive, onMounted, defineAsyncComponent, nextTick, onUnmounted } from "vue"
import _ from "lodash"
import { Search, Plus, Hide, View } from '@element-plus/icons-vue'
import { merchantPageApiPost, merchantDeleteApiDelete, merchantDetailApiGet } from "@/api/userMangement"
import useInstance from '@/hooks/useInstance';
import { useColorStore } from "@/store/common"
import addBusiness from "./components/addAndEdit.vue"
import { businessListStore } from "./pageStore"
import { useEnumStore } from "@/store/enumeration"
import { menuStore } from "@/store/menu.ts"
import mittBus from '@/utils/mitt';
/***************************************数据******************************************** */
const { sensitive } = menuStore()

const provinceStore = useColorStore()
const { twoLevelCity } = storeToRefs(provinceStore)
const { productType } = storeToRefs(useEnumStore())
const { global } = useInstance();
const { detailData, tableProp } = storeToRefs(businessListStore())
// const addBusiness = defineAsyncComponent(() => import("./components/addAndEdit.vue"))
const downList = defineAsyncComponent(() => import("@/components/downList.vue"))
const detailForm = defineAsyncComponent(()=>import('./components/detail.vue'))
const addEditRef = ref<{ show: (type: string, row?: any) => void }>()
const downListRef = ref<{ show: (title: string, row?: any) => void }>()
const detailRef = ref<{ show: (title: string, row?: any) => void }>()


const listSearch = reactive({
  pageNum: 1,
  pageSize: 20,
  condition: {
    channelMerchantCode: null,
    channelMerchantName: null,
    contactName: null,
    locationProvinceCode: null,
    locationCityCode: null
  },
  isShow: false,
    orders: ["created_time desc"],
})

const pageData = reactive({
  loadIng: false,
  tableData: [],
  total: 0,
  tableHeight: 500,
  productList: []
})
const selectTitle = ref<any>([])
const cityCode = ref<any>([])
const onlyTableRef = ref()

/***************************************方法******************************************** */
const handleView = () => {
  listSearch.isShow = !listSearch.isShow
  getData('search')
}
const showFun = (str: string) => {
  const arr = sensitive && sensitive.filter((item: any) => item.code == str)
  if (arr && arr.length) {
    return true
  }
  return false
}

const detailBtn = async (row: any) => {
  try {
    const res = await merchantDetailApiGet({ id: row.id })
    if (res.code != 20000) return
    detailRef.value?.show('edit',res.data)
  } catch (error) {

  }
}
onMounted(() => {
  selectTitle.value = tableProp.value.propsList.filter(it => it.hidden && it.label != "操作").map(item => item.prop)
  getData('search')
})




const changeValue = (val: any) => {
  if (val?.length == 1) {
    listSearch.condition.locationProvinceCode = val[0]
    listSearch.condition.locationCityCode = null
  } else if (val?.length == 2) {
    listSearch.condition.locationProvinceCode = val[0]
    listSearch.condition.locationCityCode = val[1]
  } else {
    listSearch.condition.locationProvinceCode = null
    listSearch.condition.locationCityCode = null
  }
  getData('search')
}
const getData = async (type: string) => {
  pageData.loadIng = true
  if (type === 'reset') {
    cityCode.value = []
    listSearch.condition.channelMerchantCode = null
    listSearch.condition.channelMerchantName = null
    listSearch.condition.contactName = null
    listSearch.condition.locationProvinceCode = null
    listSearch.condition.locationCityCode = null
    listSearch.pageNum = 1
    listSearch.pageSize = 20
    onlyTableRef.value.initPagination()
  }
  const res = await merchantPageApiPost(listSearch)
  if (res.code == 20000) {
    // 
    pageData.tableData = res.data.records && res.data.records.map((item: any) => {
      return {
        ...item,
        channelMerchantType: productType.value[item.channelMerchantType - 1]?.value
      }
    })
    pageData.total = res.data.total
    pageData.loadIng = false
    mittBus.emit('scrollUpdate')
  }
}

const addEdit = async (type: string, row?: any) => {
  if (type === 'add') {
    addEditRef.value?.show(type)
  } else {
    const res = await merchantDetailApiGet({ id: row.id })
    addEditRef.value?.show(type, res.data)
  }
}
const handPage = (val: { pageNum: number; pageSize: number }) => {
  listSearch.pageNum = val.pageNum;
  listSearch.pageSize = val.pageSize;
  getData("search");
};

const downLoad = () => {
  // downListRef.value?.show('渠道商下载列表','channel')

}
const DeleteBtn = async (row: any) => {
  const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.channelMerchantName}`)
  if (flag) {
    const res = await merchantDeleteApiDelete({ id: row.id })
    console.log(res.data);
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "数据删除成功"
      })
      getData('search')
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败"
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container-column {
  height: calc(100vh - 70px);
  .card-com {
    display: flex;
    flex-direction: column;
    // height: 100%;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>